package com.wangjie.binarysearch;

/**
 * @author jieshao
 * @date 2022/4/21 14:24
 *
 * 875. 爱吃香蕉的珂珂
 */
public class Test03 {
    public int minEatingSpeed(int[] piles, int h) {
        int left = 1;
        int right = 1000000000 + 1;

        while (left < right) {
            int mid = left + (right - left) / 2;
            if (f(piles, mid) <= h) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }

    // 定义：速度为 x 时，需要 f(x) 小时吃完所有香蕉，f(x) 随着 x 的增加单调递减
    int f(int[] piles, int x) {
        int hours = 0;
        for (int i = 0; i < piles.length; i++) {
            hours += piles[i] / x;
            // 每小时最多吃一堆香蕉，如果吃不完留到下一小时再吃，如果吃完了也只能等到下一小时才会吃下一堆
            if (piles[i] % x > 0) {
                hours++;
            }
        }
        return hours;
    }
}